package com.igroupes.ovineherd.handler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xxh
 * @title: ListToStringHandler
 * @projectName ovineherd-parent
 * @description: listLong转化String
 * @date 2020/12/1215:05
 */
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.BIGINT)
public class ListLongToStringHandler extends BaseTypeHandler<List> {
    private String toJsonString(List<Long> list) {
        return null != list && 0 != list.size() ? JSONObject.toJSONString(list) : null;
    }
    private List<Long> parse(String json) {
        return json != null && json.length() != 0 ? JSONObject.parseArray(json, Long.class) : new ArrayList<>();
    }
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, this.toJsonString(list));
    }

    @Override
    public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return parse( resultSet.getString(s));
    }

    @Override
    public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return parse( resultSet.getString(i));
    }

    @Override
    public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return parse( callableStatement.getString(i));
    }
}
